<template>
  <!-- 撤回弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="400px"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :inline="true"
      :rules="rules"
      label-width="100"
    >
      <el-row>
        <el-col :span="4">
          <el-form-item label="撤回日期" prop="planActualDate">
            <el-date-picker
              v-model="formData.planActualDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择日期"
              @change="getPlanWorkingForm"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "RevokeTime",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  isPm: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);
const validateTime = (rule, value) => {
  //保存时统一校验
  console.log(rule);
  const t3 = new Date(value).getTime();

  return Promise.resolve();
};

const rules = reactive({
  sonplanUserIds: [
    { required: true, message: "请输入计划人员", trigger: "change" },
    // {
    //   validator: validateUserIds,
    //   trigger: ["blur", "change"],
    // },
  ],
  sonplanBeginTime: [
    { required: true, message: "请选择计划开始时间", trigger: "change" },
    {
      validator: validateTime,
      trigger: ["blur", "change"],
    },
  ],
  planActualDate: [
    { required: true, message: "请选择生产日期", trigger: "change" },
  ],
});
const formRef = ref(ElForm);

let formData = reactive({
  details: [],
  crewId: "",
  crewName: "",
  planActualDate: getCurrentDate(),
});

watch(
  () => props.data,
  (newVal: any) => {
    // const { details } = newVal;
    // formData.details = details;
    // // Object.assign(formData, {
    // //   details,
    // // });
    // if (details?.length > 0) {
    //   getCrews();
    //   formData.details.forEach((item) => {
    //     if (item.planUserIds) {
    //       item.memberIds = item.planUserIds.split(",");
    //     }
    //   });
    //   if (details[0].crewId) {
    //     formData.crewId = details[0].crewId;
    //     getCrewMembers();
    //   }
    // }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [];
  formData.crewId = "";
  formData.crewName = "";
}

const loading = ref(false);

function handleSubmit() {
  let api;
  if (props.data.type == 1) {
    api = "/mes/mesplanworkingform/revokeBurnish";
  } else if (props.data.type == 3) {
    api = "/mes/mesplanworkingform/revokeOutsourcing";
  } else {
    api = "/mes/mesplanworkingform/revokeAloneBurnish";
  }

  formRef.value.validate(async (valid: any) => {
    if (valid) {
      ElMessageBox.confirm("是否进行撤回操作?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        loading.value = true;
        const text = "撤回";
        await request({
          url: api,
          method: "post",
          data: {
            planDate: formData.planActualDate,
          },
        }).finally(() => {
          loading.value = false;
        });
        ElMessage.success(text + `成功`);
        closeDialog();
        emit("reset-table", formData);
      });
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

async function getPlanWorkingForm() {
  if (!formData.planActualDate) {
    ElMessage.error("请选择日期");
    return;
  }
  formRef.value.clearValidate();
}

// 获取当前日期yyyymmdd
function getCurrentDate(time?: any) {
  let today = new Date();
  if (time) {
    today = new Date(time);
  }
  let year = today.getFullYear();
  let month = (today.getMonth() + 1).toString().padStart(2, "0");
  let day = today.getDate().toString().padStart(2, "0");
  return year.toString() + "-" + month + "-" + day;
}
</script>
